package com.example.javabasic.thread.classone.demo5;


import com.sun.deploy.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * 查看被什么方法调用  调用链 线程执行过程
 */
public class StackTrace {

    public static void main(String[] args) {
        StackTrace s = new StackTrace();
        TestA instance = s.getInstance();
        Thread t = new Thread(()->{
            try {
                instance.test1();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        });
        t.start();
    }

    public TestA getInstance(){
        return new TestA();
    }

    public class TestA{
        public void test1() throws ClassNotFoundException {
            System.out.println("调用test1");
            TestB b = new TestB();
            b.test2();
        }
    }

    public class TestB{
        public void test2() throws ClassNotFoundException {
            System.out.println("调用test2");
            //输出方法调用过程
//            Arrays.stream(Thread.currentThread().getStackTrace()).forEach(n->{
//                Optional.of(n.getClassName()).ifPresent(System.out::println);
//            });
            StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
            List<String> list = new ArrayList<>();
            for (int i = stackTrace.length-1; i > 0; i--) {
                StackTraceElement stackTraceElement = stackTrace[i];
                Class<?> aClass = Class.forName(stackTrace[i].getClassName());
                String simpleName = aClass.getSimpleName();
                list.add(simpleName+":"+stackTraceElement.getMethodName());
            }
            System.out.println(StringUtils.join(list,"->"));
        }
    }

}
